package br.perfiman.faces;

import java.util.List;

import br.perfiman.model.AbstractEntity;
import br.perfiman.service.AbstractService;
import br.perfiman.utils.Constants;

public abstract class AbstractBean<Entity extends AbstractEntity> extends BaseBean {
	protected AbstractService<Entity> service;

	private Entity entity;
	private List<Entity> entities;

	public AbstractBean() throws Exception {
		service = getService();
	}

	protected abstract AbstractService<Entity> getService() throws Exception;

	public String save() throws Exception{
		if(getEntity().getEntityId() == null) { //new
			service.insert(entity);
			addInfoMessage(Constants.ENTITY_ADDED);
		} else {//edit
			service.update(entity);
			addInfoMessage(Constants.ENTITY_UPDATED);
		}
		return retrieveAll();
	}

	public String retrieveById() throws Exception {
		entity = service.retrieveById(entity.getEntityId());
		return retrieveAll();
	}

	public String remove() throws Exception {
		service.remove(entity);
		addInfoMessage(Constants.ENTITY_REMOVED);
		return retrieveAll();
	}

	public String retrieveAll() throws Exception {
		entities = service.retrieveAll();
		return null;
	}

	public List<Entity> getEntities() {
		return entities;
	}

	public Entity getEntity() {
		return entity;
	}

	public void setEntities(List<Entity> entities) {
		this.entities = entities;
	}

	public void setEntity(Entity entity) {
		this.entity = entity;
	}
}
